# Random Walk + Drift und
# Indices: 
# i: polls
# j: weeks
# k: parties
# l: pollsters


model	{
	
	for (i in 1:length(anteil[,1]))
	{
		anteil[i, 1:6] ~ dmulti(pi[i,1:6], befragte[i])
		for (k in 2:6)
		{
			linpred[i,k] <- a[hypweek[i],k] + z[pollster[i],k]

			
		}
		linpred[i,1] <- 0 # fix
		# loop ueber Wahrscheinlichkeiten
		for (k in 1:6)
		{
			pi[i,k] <- exp(linpred[i,k]) / (exp(linpred[i,1]) + exp(linpred[i,2]) + exp(linpred[i,3]) + exp(linpred[i,4]) + exp(linpred[i,5]) + exp(linpred[i,6]))
		}
	}

# random effect for week
	    for (k in 2:6) 
	    {
		    for (j in 2:J)
	    	    {
			mu[j,k] <- a[j-1,k] + drift[k]
# Drift
			a[j,k] ~ dnorm(mu[j,k], tau[k])
	    		}
		a[1,k] ~ dunif(partystartlogits[k,1],partystartlogits[k,2])
		tau[k] <- pow(sigma[k], -2)
		sigma[k] ~ dunif (0, 100)

                drift[k] ~ dnorm(0,0.0001)

  	    }

# random effect for pollster
	    for (k in 2:6) 
	    {
		    for (l in 1:6)
	    	    {
			mu.z[l,k] ~ dnorm (0, .0001)
			z.star[l,k] ~ dnorm(mu.z[l,k], tau.z[k])
			z[l,k] <- z.star[l,k] - mean(z.star[1:6,k])
	    		}
# Initi
		tau.z[k] <- pow(sigma.z[k], -2)
		sigma.z[k] ~ dunif (0, 100)



  	    }

# Predict 
	    for (k in 2:6) 
	    {
		    for (j in J+1:39)
	    	    {
			mu[j,k] <- a[j-1,k] + drift[k]
			a[j,k] ~ dnorm(mu[j,k], tau[k])
		    }
	   }


# Get per cent
	for (j in 1:39) {
		a[j,1] <- 0 # fix
	    		for (k in 1:6)
				{
				T[j,k] <- exp(a[j,k]) / (exp(a[j,1]) + exp(a[j,2]) + exp(a[j,3]) + exp(a[j,4]) + exp(a[j,5]) + exp(a[j,6]))
				}


		fdpin[j]  <- T[j,4] >= 0.05
		coalmaj[j] <- (T[j,1] + T[j,4]) > (T[j,2] + T[j,3] + T[j,5])
		redgreenmaj[j]  <- (T[j,2] + T[j,3]) > (T[j,1] + T[j,4] + T[j,5])
				}		

	    

			}

